/* Copyright 2001,2002,2003 NAH6 BV
 * All Rights Reserved
 *
 *  $Header: /var/lib/cvs/secphone/ui/sppim/sppim.cpp,v 1.6 2003/11/21 16:12:58 itsme Exp $
 *
 *
 *  this is the contacts app context menu plugin, it is registered at 
 *  application install, by adding registry keys under
 *     HKLM\Software\Microsoft\PimApps\PimExtensions\Contacts\AddIns
 *
 */

#include <windows.h>
#include <tchar.h>
#include "sppim.h"

#ifdef SPPIM_EXPORTS
#   define SPPIMEXPORT extern "C" __declspec(dllexport)
#else
#   define SPPIMEXPORT extern "C" __declspec(dllimport)
#endif

typedef enum tagPIMTYPE
{
   PT_CALENDAR = 0,
   PT_TASKS,
   PT_CONTACT
} PIMTYPE;

struct EnumParams {
    TCHAR *wintitle;
    HWND hWnd;
};

BOOL CALLBACK EnumCloseProc(HWND hwnd, LPARAM lParam)
{
    struct EnumParams *ep= (struct EnumParams *)lParam;

    TCHAR buf[256];
    GetWindowText(hwnd, buf, 256);

    if (_tcscmp(buf, ep->wintitle)==0)
    {
        ep->hWnd= hwnd;
        return FALSE;
    }
    return TRUE;
}

HWND FindWindowByTitle(TCHAR *wintitle)
{
    struct EnumParams ep;
    ep.wintitle= wintitle;
    ep.hWnd= NULL;

    if (!EnumWindows(EnumCloseProc, (DWORD)&ep))
        return NULL;

    return ep.hWnd;
}

bool GetRegistryString(HKEY hive, TCHAR *path, TCHAR *name, TCHAR *strbuf, int maxlen)
{
    HKEY hk;
    // doc says it needs a 'class' string, everybody else says class don't exist.
    if (ERROR_SUCCESS!=RegOpenKeyEx(hive, path, 0, 0, &hk))
    {
        return false;
    }

    DWORD valtype;
    DWORD vallen= maxlen;
    if (ERROR_SUCCESS!=RegQueryValueEx(hk, name, 0, &valtype, (BYTE*)strbuf, &vallen))
    {
        return false;
    }
    RegCloseKey(hk);
    if (valtype!=REG_SZ)
    {
        return false;
    }
    strbuf[maxlen-1]=0;

    return true;
}

#define REGISTRY_PATH L"Software\\CryptoPhone"
void StartCryptoPhoneWithOid(DWORD oid)
{
    WCHAR cryptophone_exefile[MAX_PATH];
    WCHAR cryptophone_cmdline[64];
    PROCESS_INFORMATION procinfo;

    if (!GetRegistryString(HKEY_CURRENT_USER, REGISTRY_PATH, L"exepath",
        cryptophone_exefile, MAX_PATH))
        _tcsncpy(cryptophone_exefile, L"CryptoPhone.exe", MAX_PATH);

    _snwprintf(cryptophone_cmdline, 64, L"-oid %08lx", oid);
    if (!CreateProcess(cryptophone_exefile, cryptophone_cmdline, NULL, NULL, 
            0, 0, NULL, NULL, NULL, &procinfo))
            return;

    CloseHandle(procinfo.hThread);
    CloseHandle(procinfo.hProcess);
}
SPPIMEXPORT void CePimCommand(HWND hWnd, PIMTYPE ptData, UINT uDataCount, HANDLE *rghData, void *pReserved)
{
    if (uDataCount!=1)
        return;

    HWND hSPWnd= FindWindowByTitle(L"CryptoPhone");
    if (hSPWnd!=NULL)
        PostMessage(hSPWnd, WM_SP_MAKECALL, 0, (DWORD)*rghData);
    else
        StartCryptoPhoneWithOid((DWORD)*rghData);
}

